package com.oocl.tm.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.HashMap;

import com.oocl.tm.clientThread.ClientThread;
import com.oocl.tm.log4j.Log4j;
import com.oocl.tm.protocol.MsgPackage;
import com.oocl.tm.protocol.Operation;
import com.oocl.tm.repository.ClientsDBFactory;
import com.oocl.tm.service.ChatService;
import com.oocl.tm.service.ExitService;
import com.oocl.tm.service.LoginService;
import com.oocl.tm.service.NoticeService;
import com.oocl.tm.service.ServerService;
import com.oocl.tm.service.ShakeService;
import com.oocl.tm.util.JsonUtil;

public class ServerServiceImpl implements ServerService {

	private Socket client;
	private OutputStream out;
	private InputStream in;
	private MsgPackage mp;

	public ServerServiceImpl(Socket client, InputStream in, OutputStream out) throws IOException {
		this.client = client;
		this.out = out;
		this.in = in;
	}

	@Override
	public MsgPackage getMsgPackage(){
		mp = JsonUtil.streamToMsgPackage(in);	
		return mp;
	}

	/**
	 * 根据 MsgPackage 头部 Operation 分流
	 */
	public void process() throws IOException{
		Log4j.getLogger().info("[ server had received： ] "+mp.toString());
		switch (mp.getOperation()) {
			case SHAKE: 
				ShakeService ss = new ShakeServiceImpl(mp);
				ss.transmitMsgPt();
				break;
				
			case CHAT:
				ChatService cs = new ChatServiceImpl(mp);
				cs.transmitMsgPt();
				break;
				
			case LOGIN:
				LoginService ls = new LoginServiceImpl(out, mp);
				NoticeService ns = new NoticeServiceImpl(out);
				ls.refreshOutputs();
				ls.recordOnline();
				Log4j.getLogger().info("[ current online: ] "+ClientsDBFactory.getClientsList().toString());
				ns.noticeOnline();
				break;
				
			case EXIT:
				ExitService es = new ExitServiceImpl(mp, out);
				es.delOneOutput();
				es.refreshOffline();
				es.noticeOnline();
				in.close();
				client.close();
				Log4j.getLogger().info(mp.getSender()+" [ normal exit ]");
				break;
				
			default:
				break;
		}
	}
}
